import Taro, { Component } from '@tarojs/taro'
import { View } from '@tarojs/components'
import './index.scss'
import until from '../../untils/lyUntils'

const paddBoth = 10;//组件相对于左右边距

export default class Index extends Component {
    static defaultProps = {
        onLyClick: () => { },//组件点击事件
        bgColor: 'red'//组件背景颜色
    }
    constructor(props) {
        super(props)
        this.state = {
            justInPage: true,
            offl: paddBoth,
            offt: 0,
            w: 0,
            h: 0,
            pageSize: 0
        }
    }
    componentWillMount() { }
    componentDidMount() {
        until.getDomInfo('#moveButton', this.$scope).then((rect) => {
            this.setState({
                justInPage: false,
                offl: Taro.getSystemInfoSync().windowWidth - rect.width - paddBoth,
                offt: Taro.getSystemInfoSync().windowHeight * 0.8,//默认距离顶部80%
                w: rect.width,
                h: rect.height,
                pageSize: Taro.getSystemInfoSync()
            })
        })
    }
    componentWillUnmount() { }
    componentDidShow() { }
    componentDidHide() { }
    touchmove(e) {
        e.stopPropagation();
        this.setState({
            offl: e.touches[0].clientX - this.state.w / 2,
            offt: e.touches[0].clientY - this.state.h / 2
        })
    }
    touchEnd(e) {
        e.stopPropagation();
        if (e.changedTouches[0].clientX > (this.state.pageSize.windowWidth - this.state.w / 4) / 2) {
            this.setState({
                offl: this.state.pageSize.windowWidth - this.state.w - paddBoth
            })
        } else if (e.changedTouches[0].clientX < (this.state.pageSize.windowWidth - this.state.w / 4) / 2) {
            this.setState({
                offl: paddBoth
            })
        }

        if (e.changedTouches[0].clientY < 0) {
            this.setState({
                offt: paddBoth
            })
        } else if (e.changedTouches[0].clientY > (this.state.pageSize.windowHeight - this.state.w)) {
            this.setState({
                offt: this.state.pageSize.windowHeight - (this.state.w + 48 + paddBoth)
            })
        }
    }
    deal() {
        this.props.onLyClick()
    }
    render() {
        let { offl, offt, justInPage } = this.state;
        let { bgColor } = this.props;
        return (
            <View className='moveButton' id='moveButton' style={{
                left: `${offl}px`,
                top: `${offt}px`,
                opacity: justInPage ? 0 : 100,
                backgroundColor: bgColor
            }} onTouchMove={this.touchmove} onTouchEnd={this.touchEnd} onClick={this.deal.bind(this)}
            >
                {this.props.children}
            </View>
        )
    }
}

